﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
//using System.Web.UI.WebControls;
using System.Linq;
using FineUI;
using System.Data;
using Newtonsoft.Json.Linq;
using AspNet = System.Web.UI.WebControls;
using IHISCETeim.Model;
using IHISCETeim.Library;
using IHISCETeim.BLL;

namespace IHISCETeim.Web.MachineSys.SysBasic
{
    public partial class ORolePowerList : PageBase
    {
        protected override Permission[] PowerKey
        {
            get
            {
                return new Permission[] { Permission.修改, Permission.新增, Permission.删除 };
            }
        }
        protected override string DWZRef
        {
            get { return "ORoleList"; }
        }

        #region Page_Load

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadData();
            }
        }

        private void LoadData()
        {
            // 权限检查
           // CheckPowerWithButton("CoreRolePowerEdit", btnGroupUpdate);


            string deleteScript = Confirm.GetShowReference("删除选中行？", String.Empty, MessageBoxIcon.Question, Grid1.GetDeleteSelectedReference(), String.Empty);
            // 新增数据初始值
            JObject defaultObj = new JObject();
            defaultObj.Add("RoleName", "");
            //defaultObj.Add("IsAgent","0");
            defaultObj.Add("Delete", String.Format("<a href=\"javascript:;\" onclick=\"{0}\"><img src=\"{1}\"/></a>", deleteScript, IconHelper.GetResolvedIconUrl(Icon.Delete)));
            // 在第一行新增一条数据
            this.btnAddRole.OnClientClick = Grid1.GetAddNewRecordReference(defaultObj, true);
            // 重置表格
           // btnAddRole.OnClientClick = Grid1.GetRejectChangesReference();


            // 每页记录数
            Grid1.PageSize = 9999;
            BindGrid();

            // 默认选中第一个角色
            Grid1.SelectedRowIndex = 0;

            // 每页记录数
            Grid2.PageSize = 9999;
            BindGrid2();
        }

        #region
        private DataTable _ALLMenuDT;
        private DataTable _AllFunDT;
        private DataTable ALLMenuDT
        {
            get
            {
                if (_ALLMenuDT == null)
                    _ALLMenuDT = OMenuController.GetAllOMenu();
                return _ALLMenuDT;
            }
        }

        private DataTable AllFunDT
        {
            get
            {
                if (_AllFunDT == null)
                    _AllFunDT = OMenuController.GetAllOMenuPermission();
                return _AllFunDT;
            }
        }

        private List<int> _AllRoleFun;
        private List<int> AllRoleFun
        {
            get
            {
                if (_AllRoleFun == null)
                {
                    _AllRoleFun = new List<int>();
                    List<ORoleFunctionInfo> list = ORoleController.GetRoleFunctionByRoleId(RoleId);
                    foreach (ORoleFunctionInfo item in list)
                    {
                        _AllRoleFun.Add(item.FunId);
                    }


                }
                return _AllRoleFun;
            }
        }

        private int RoleId
        {
            get {
                return Convert.ToInt32(Grid1.DataKeys[Grid1.SelectedRowIndex][0]);
            }
        }

        /// <summary>
        /// 获取一级菜单名称
        /// </summary>
        /// <param name="ParMenuId"></param>
        /// <returns></returns>
        private string GetParMenuName(int ParMenuId)
        { 
            OMenuInfo obj=  OMenuController.GetMenuByMenuId(ParMenuId);
            string menuname=obj.MenuName;
            if (obj.ParMenuId > 0)
                menuname = GetParMenuName(obj.ParMenuId) + "-" + menuname;
            return menuname;
        }
        #endregion

        private void BindGrid()
        {
            //IQueryable<Role> q = DB.Roles;

            //// 排列
            //q = Sort<Role>(q, Grid1);

            Grid1.DataSource = ORoleController.GetAll();
            Grid1.DataBind();
          
        }

        //private Dictionary<string, bool> _currentRolePowers = new Dictionary<string, bool>();

        private void BindGrid2()
        {
           // RoleId =Convert.ToInt32( Grid1.DataKeys[Grid1.SelectedRowIndex][0]);

            DataTable menudt=  ALLMenuDT.Select("DWZHref<>'#' AND ParMenuId<>0 and IsUsed=1 ").CopyToDataTable();
            menudt.DefaultView.Sort = " ParMenuId ASC ";
            menudt = menudt.DefaultView.ToTable();
            Grid2.DataSource = menudt;
            Grid2.DataBind();            

        }

        #endregion

        #region Grid1 Events

        protected void Grid1_RowClick(object sender, FineUI.GridRowClickEventArgs e)
        {
            BindGrid2();
        }
        protected void Grid1_RowCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName == "ViewSub")
            {
                Grid1.SelectedRowIndex = e.RowIndex;
              //  int ParId = Convert.ToInt32(gdPar.DataKeys[gdPar.SelectedRowIndex][0]);
               // BindGrid2(ParId);
                BindGrid2();
            }
           
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            // 删除现有数据
            List<int> deletedRows = Grid1.GetDeletedList();
            foreach (int rowIndex in deletedRows)
            {
                int rowID = Convert.ToInt32(Grid1.DataKeys[rowIndex][0]);
                //DeleteRowByID(rowID);
                ORoleController.Delete(rowID);
                //AgentMainFaultControlller.Delete(rowID);
            }

            // 修改的现有数据
            Dictionary<int, Dictionary<string, object>> modifiedDict = Grid1.GetModifiedDict();
            foreach (int rowIndex in modifiedDict.Keys)
            {
                if (modifiedDict[rowIndex].ContainsKey("RoleName"))
                {
                    int rowID = Convert.ToInt32(Grid1.DataKeys[rowIndex][0]);
                    ORoleInfo obj = ORoleController.GetById(rowID);
                    obj.RoleName = modifiedDict[rowIndex]["RoleName"].ToString();
                    ORoleController.Update(obj);
                    //AgentMainFaultControlller.Update(obj);
                }
            }


            // 新增数据
            List<Dictionary<string, object>> newAddedList = Grid1.GetNewAddedList();
            for (int i = 0; i < newAddedList.Count; i++)
            {
                //DataRow rowData = CreateNewData(table, newAddedList[i]);
                //table.Rows.Add(rowData);
                ORoleInfo obj = new ORoleInfo();
                obj.RoleName = newAddedList[i]["RoleName"].ToString();
                obj.IsAgent =false;
                ORoleController.Add(obj);
            }

            BindGrid(); 

            Alert.Show("数据保存成功");
        }
        protected void Grid1_PreDataBound(object sender, EventArgs e)
        {
            LinkButtonField deleteField = Grid1.FindColumn("Delete") as LinkButtonField;
            deleteField.OnClientClick = Confirm.GetShowReference("删除选中行？", String.Empty, MessageBoxIcon.Question, Grid1.GetDeleteSelectedReference(), String.Empty);
        }
        #endregion

        #region Grid2 Events

        protected void Grid2_RowDataBound(object sender, FineUI.GridRowEventArgs e)
        {
            AspNet.CheckBoxList ddlPowers = (AspNet.CheckBoxList)Grid2.Rows[e.RowIndex].FindControl("ddlPowers");
            AspNet.Label lbparmenuname = (AspNet.Label)Grid2.Rows[e.RowIndex].FindControl("lbParMenuName");
            int ParMenuId = Convert.ToInt32((e.DataItem as DataRowView)["ParMenuId"]);
            lbparmenuname.Text = GetParMenuName(ParMenuId);

            int MenuId = Convert.ToInt32((e.DataItem as DataRowView)["MenuId"]);
            DataRow[] funDT = AllFunDT.Select("MenuID=" + MenuId.ToString());
            //IGrouping<string, Power> powers = e.DataItem.GetType().GetProperty("Powers").GetValue(e.DataItem, null) as IGrouping<string, Power>;

            foreach (DataRow power in funDT)
            {
                AspNet.ListItem item = new AspNet.ListItem();
                item.Value = power["funid"].ToString();
                item.Text = power["PermissionTag"].ToString();
               // item.Attributes["data-qtip"] = power.Name;

                if (AllRoleFun.Contains(Convert.ToInt32( power["funid"].ToString())))
                {
                    item.Selected = true;
                }
                else
                {
                    item.Selected = false;
                }

                ddlPowers.Items.Add(item);
            }
        }
        
        protected void btnGroupUpdate_Click(object sender, EventArgs e)
        {

            //// 在操作之前进行权限检查
            //if (!CheckPower("CoreRolePowerEdit"))
            //{
            //    CheckPowerFailWithAlert();
            //    return;
            //}

            //int roleId = GetSelectedDataKeyID(Grid1);
            //if (roleId == -1)
            //{
            //    return;
            //}

            //// 当前角色新的权限列表
            List<int> newPowerIDs = new List<int>();
            for (int i = 0; i < Grid2.Rows.Count; i++)
            {
                AspNet.CheckBoxList ddlPowers = (AspNet.CheckBoxList)Grid2.Rows[i].FindControl("ddlPowers");
                foreach (AspNet.ListItem item in ddlPowers.Items)
                {
                    if (item.Selected)
                    {
                        newPowerIDs.Add(Convert.ToInt32(item.Value));
                    }
                }
            }

            if (RoleId < 0)
                return;
            
            
            ORoleInfo obj = ORoleController.GetById(RoleId);
            string funids = string.Join(",", newPowerIDs.ToArray());
            if (ORoleController.Update(obj, funids))
                Alert.Show("当前角色的权限更新成功！");
            else
                Alert.Show("当前角色的权限更新失败！");

            //Role role = DB.Roles.Include(r => r.Powers).Where(r => r.ID == roleId).FirstOrDefault();

            //ReplaceEntities<Power>(role.Powers, newPowerIDs.ToArray());

            //DB.SaveChanges();


            //Alert.ShowInTop("当前角色的权限更新成功！");
        }


        #endregion

       

       

       
        
    }
}